<?php


namespace app\api\controller;


use app\admin\model\MallWithdrawRecord;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use app\common\controller\IndexController;
use app\api\library\user\updateUserName;
use app\api\library\user\updateUserPhone;
use app\api\library\user\getUserInfo;
use app\api\library\user\getUserTradeInfo;
use app\api\library\user\getUserTradeType;
use EasyAdmin\upload\Uploadfile;
use think\Exception;
use think\facade\Db;
use think\facade\Filesystem;

class User extends IndexController
{
    /**
     * 修改用户姓名
     */
    public function updateUserName()
    {
        $req = $this->run(WEB_KEY);
//        $req = request()->param();
        //处理参数
        $display = [
            ['userId', 'ui', 'int'],
            ['name', 'ne', 'str'],
        ];
        //校验参数
        $param = _displayParam($req, $display);
        
        
        updateUserName\V::run($param);
    }
    /**
     * 修改用户电话
     */
    public function updateUserPhone()
    {
        $req = $this->run(WEB_KEY);
//        $req = request()->param();
        //处理参数
        $display = [
            ['userId', 'ui', 'int'],
            ['mobile', 'me', 'str'],
            ['code', 'ce', 'str'],
        ];
        //校验参数
        $param = _displayParam($req, $display);
        
        
        updateUserPhone\V::run($param);
    }
    /**
     * 修改用户头像
     */
    public function updateUserAvatar()
    {
        
        $userId       = _checkEmptyParam(input('ui'), '用户不能为空');
        $data         = [
            'upload_type' => $this->request->post('upload_type'),
            'file'        => $this->request->file('at'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data[ 'upload_type' ]) && $data[ 'upload_type' ] = $uploadConfig[ 'upload_type' ];
        $rule = [
            'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
            'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload          = Filesystem::disk('public')->putFile('userUpload', $data[ 'file' ]);
            $completeFileUrl = request()->domain() . '/' . str_replace(DIRECTORY_SEPARATOR, '/', $upload);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload) {
            if (false === MallUser::update(['avatar_url' => $completeFileUrl], ['id' => $userId])) {
                _outPut(204, '', '修改失败');
            }
            $userInfo = MallUser::where(['id' => $userId])->find();
            $res      = [
                [
                    'id'         => $userInfo[ 'id' ],
                    'avatar_url' => $userInfo[ 'avatar_url' ],
                    'name'       => $userInfo[ 'name' ],
                    'balance'    => getPrice($userInfo[ 'balance' ]),
                ],
            ];
            _outPut(200, $res);
        } else {
            $this->error($upload[ 'msg' ]);
        }
    }
    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $req = $this->run(WEB_KEY);
//        $req = request()->param();
        //处理参数
        $display = [
            ['userId', 'ui', 'int'],
        ];
        //校验参数
        $param = _displayParam($req, $display);
        
        
        getUserInfo\V::run($param);
    }
    /**
     * 获取用户交易记录
     */
    public function getUserTradeInfo()
    {
        $req = $this->run(WEB_KEY);
//        $req = request()->param();
        //处理参数
        $display = [
            ['userId', 'ui', 'int'],
            ['type', 'te', 'int', 0],
            ['date', 'de', 'str'],
            ['page', 'pe', 'int', 1],
            ['limit', 'lt', 'int', 3],
        ];
        //校验参数
        $param = _displayParam($req, $display);
        
        
        getUserTradeInfo\V::run($param);
    }
    /**
     * 提现申请
     */
    public function withDraw()
    {
        $userId  = _checkEmptyParam(input('ui'), '用户不能为空');
        $type    = _checkEmptyParam(input('te'), '收款方式不能为空');
        $amount  = _checkEmptyParam(input('at'), '收款金额不能为空');
        $name    = _checkEmptyParam(input('ne'), '姓名不能为空');
        $account = input('aat');
        $image   = $this->request->file('ie');
        $cache   = cache('withdraw' . $userId);
        if ($cache == 1) {
            _throwNewException('订单正在处理中');
        }
        cache('withdraw' . $userId, 1, 2);
        $code   = _checkEmptyParam(input('ce'), '验证码不能为空');
        $mobile = MallUser::where('id', $userId)->value('mobile');
        //查询用户最新的一次验证码
        $userCode = Db::name('mall_mobile_msg')->where([['mobile', '=', $mobile], ['code', '=', $code]])->find();
        if (empty($userCode)) {
            _outPut(204, '', '验证码错误');
        }
        if ($userCode[ 'expire_time' ] < time()) {
            _outPut(204, '', '验证码已过期');
        }
        if ($type == 3) {
            _checkEmptyParam($account, '支付宝账号不能为空');
        } else {
            _checkEmptyParam($image, '收款码不能为空');
        }
        if ( !empty($image)) {
            $data         = [
                'upload_type' => $this->request->post('upload_type'),
                'file'        => $image,
            ];
            $uploadConfig = sysconfig('upload');
            empty($data[ 'upload_type' ]) && $data[ 'upload_type' ] = $uploadConfig[ 'upload_type' ];
            $rule = [
                'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
                'file|文件'              => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
            ];
            $this->validate($data, $rule);
            try {
                $upload          = Filesystem::disk('public')->putFile('userUpload', $data[ 'file' ]);
                $completeFileUrl = request()->domain() . '/' . str_replace(DIRECTORY_SEPARATOR, '/', $upload);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $balance    = MallUser::where('id', $userId)->value('balance');
        $amount     = $amount * 100;
        $surBalance = $balance - $amount;
        if ($surBalance < 0) {
            _outPut(204, [], '余额不足');
        }
        $addData = [
            'user_id'     => $userId,
            'name'        => $name,
            'type'        => $type,
            'status'      => 0,
            'amount'      => $amount,
            'balance'     => $surBalance,
            'account'     => $account,
            'create_time' => time(),
            'update_time' => time(),
        ];
        if (isset($upload)) {
            $addData[ 'image' ] = $completeFileUrl;
        }
        try {
            //开启事务
            Db::startTrans();
            $id = MallTradeRecordLog::addRecord($userId, 0, $amount, $surBalance, $type + 13);
            //减去余额
            if (false === MallUser::where([['id', '=', $userId]])->update(['balance' => $surBalance])) {
                _throwNewException('提现申请失败');
            }
            $Record = MallWithdrawRecord::insertGetId($addData);
            if (false === $Record) {
                _throwNewException('提现申请失败');
            }
            Db::table('ea_mall_trade_record_log')->where(['id' => $id])->update(['order_id' => $Record]);
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            _outPut(204, '', $e->getMessage());
        }
        _outPut(200);
    }
    
    /**
     * 修改用户电话
     */
    public function getUserTradeType()
    {
        $req = $this->run(WEB_KEY);
//        $req = request()->param();
        //处理参数
        $display = [
            ['userId', 'ui', 'int'],
        ];
        //校验参数
        $param = _displayParam($req, $display);
        
        
        getUserTradeType\V::run($param);
    }
}